﻿using System;
using System.Linq;
using System.Net;
using System.IO;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Formatting;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;

namespace HearthDb.EnumsGenerator
{
	internal class Program
	{
		private const string File = "../../../../HearthDb/Enums/Enums.cs";
		static void Main()
		{
			ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
			string enums;
			var url = "https://api.hearthstonejson.com/v1/enums.cs?" + DateTime.Now.Ticks;
			Console.WriteLine($"Fetching {url}...");
			using(var wc = new WebClient())
				enums = wc.DownloadString(url);

			Console.WriteLine($"Generating namespace...");
			var header = ParseLeadingTrivia(@"/* THIS FILE WAS GENERATED BY HearthDb.EnumsGenerator. DO NOT EDIT. */" + Environment.NewLine + Environment.NewLine);
			var members = ParseCompilationUnit(enums).Members;
			var first = members.First().WithLeadingTrivia(header);
			var @namespace = NamespaceDeclaration(IdentifierName("HearthDb.Enums")).AddMembers(new [] {first}.Concat(members.Skip(1)).ToArray());

			Console.WriteLine($"Formatting namespace...");
			var root = Formatter.Format(@namespace, new AdhocWorkspace());

			var rootString = root.ToString();
			string prevString;
			using (var sr = new StreamReader(File))
				prevString = sr.ReadToEnd();

			if (prevString != rootString)
			{
				Console.WriteLine($"Saving to '{File}'...");
				using(var sr = new StreamWriter(File))
					sr.Write(root.ToString());
				Console.WriteLine("Done. Press any key to exit.");
			}
			else
				Console.WriteLine($"No changes. Press any key to exit.");

			Console.ReadKey();
		}
	}
}
